package com.example.demo.Controller;


import com.example.demo.common.AppResult;
import com.example.demo.common.ResultCode;
import com.example.demo.config.AppConfig;
import com.example.demo.model.User;
import com.example.demo.services.IUserService;
import com.example.demo.utils.MD5Util;
import com.example.demo.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

// 对Controller层进行说明
@Api(tags = "用户接口")

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

        @Resource
        private IUserService userService;

        //用户注册
        @ApiOperation("用户注册")
        @RequestMapping("/register")
        public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull  String username,
                                  @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                                  @ApiParam("密码") @RequestParam("password") @NonNull String password,
                                  @ApiParam("重复密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
            // NonNull注解 可实现以下判断是否为空的功能
//            if(StringUtil.isEmpty(username)
//                    || StringUtil.isEmpty(nickname)
//                    || StringUtil.isEmpty(password)
//                    || StringUtil.isEmpty(passwordRepeat)){
//                //任意值为空 就返回错误信息
//                return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
//            }

            // 判断密码是否一致
            if(!password.equals(passwordRepeat)){
                log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
                return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
            }

            User user=new User();
            user.setUsername(username);
            user.setNickname(nickname);
            user.setPassword(password);

            // 处理密码
            //盐
            String salt= UUIDUtil.UUID_32();
            //加密后的密码
            String encryptedPassword= MD5Util.md5Salt(password,salt);
            //设置加密后的密码
            user.setPassword(encryptedPassword);
            user.setSalt(salt);

            userService.createNormalUser(user);

            return AppResult.success();
        }


        //用户登录
        @ApiOperation("用户登录")
        @RequestMapping("/login")
        public AppResult login(HttpServletRequest request,
                               @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                                   @ApiParam("密码") @RequestParam("password") @NonNull String password
                               ){
            // 1.调用Service层的login方法
            User user= userService.login(username, password);
            // 2.如果登录成功 把User设置到session中
            if(user==null){
                //打印日志
                log.warn(ResultCode.FAILED_LOGIN.toString());
                // 登录失败
                return AppResult.failed(ResultCode.FAILED_LOGIN);
            }

            //true: 没有session时，就创建一个新的
            HttpSession session=request.getSession(true);
            session.setAttribute(AppConfig.USER_SESSION_KEY,user);

            // 3.返回结果
            return AppResult.success();

        }


    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult getUserInfo(HttpServletRequest request,                   // required = false 非必填参数
                                 @ApiParam("用户id") @RequestParam(value = "id",required = false) Long id ){

          User user=null;
          //根据Id判断是否从session中获取用户信息
           if(id==null){
               //1.ID为空，从session中获取用户信息
               HttpSession session=request.getSession(false);
               if(session==null || session.getAttribute(AppConfig.USER_SESSION_KEY)==null){
                    //打印日志
                    log.warn(ResultCode.FAILED_FORBIDDEN.toString());
                    // 返回
                    return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
               }
               //从session中获取用户信息
                user= (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
           }else{
               // 2.ID不为空，从数据库中获取用户信息
                user=userService.selectById(id);

               //3.如果用户信息为空，返回错误信息
               if(user==null){
                   //打印日志
                   log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
                   // 登录失败
                   return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
               }
           }

            return AppResult.success(user);

    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
            //1.从session中获取用户信息
            HttpSession session=request.getSession(false);
            //2.判断是否为空
            if(session!=null){
                log.info("退出成功");
                session.invalidate();
            }
            //返回结果
            return AppResult.success("退出成功");
    }






















}
